package main

import (
	"context"
	"fmt"
	"time"

	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"github.com/apache/rocketmq-client-go/v2/producer"
)

type OrdderListener struct{}

func (o *OrdderListener) ExecuteLocalTransaction(msg *primitive.Message) primitive.LocalTransactionState {
	fmt.Println("开始执行本地逻辑")
	time.Sleep(time.Second * 3)
	fmt.Println("执行本地逻辑失败")

	return primitive.UnknowState
}

func (o *OrdderListener) CheckLocalTransaction(msg *primitive.MessageExt) primitive.LocalTransactionState {
	fmt.Println("recketmq的消息回查")
	time.Sleep(time.Second * 5)
	return primitive.CommitMessageState
}

func main() {
	p, err := rocketmq.NewTransactionProducer(
		&OrdderListener{},
		producer.WithNameServer([]string{"192.168.10.130:9876"}),
	)
	if err != nil {
		fmt.Println("连接错误：", err)
	}
	//启动
	if err = p.Start(); err != nil {
		fmt.Println("启动错误：", err)
	}
	res, err := p.SendMessageInTransaction(context.Background(), primitive.NewMessage("TransTopic", []byte("this is TransTopic2")))
	if err != nil {
		fmt.Printf("send message error: %s\n", err)
	} else {
		fmt.Printf("send message success: result=%s\n", res.String())
	}
	time.Sleep(time.Hour)
	if err = p.Shutdown(); err != nil {
		fmt.Printf("shutdown producer error: %s", err.Error())
	}
}
